<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;

class XhsReport extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhsreport:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$xhswhere = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $xhswhere, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['userType', '=', 10 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['bazaarId','=', $bazaarId ] );
		  array_push( $xhswhere, ['bazaarId','=', $bazaarId ] );
		}

		$username = $request->param('username', '', 'trim');
		if($username) {
			array_push( $where, ['username', 'like',  "%{$username}%" ] );
			array_push( $xhswhere, ['username', 'like',  "%{$username}%" ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			array_push( $xhswhere, ['datetime', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, false) ] );
		} else {
			array_push( $xhswhere, ['datetime', 'between', cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), false) ] );
		}

		$searchArray = Db::table('cfg_xhs')->field('`username`, `update`, sum(`spent_str`) as `spent_str`, sum(`impression_str`) as `impression_str`,
			sum(`click_str`) as `click_str`, sum(`ctr_str`) as `ctr_str`, sum(`acp_str`) as `acp_str`')->where($xhswhere)
				->group('username')->select()->toArray();

		$paginate = Db::name('cfg_expand')->where($where)->field('id,username,balance,budget,status,cost,userStat,lastDatetime,bazaarId')->order($sort, $order)->paginate($limit);

		$total = $paginate->total();
		$items = $paginate->items();
		foreach ( $items as &$value ) {
			$value['impression_str'] = 0;
			$value['spent_str'] = 0;
			$value['click_str'] = 0;
			$value['ctr_str'] = 0;
			$value['acp_str'] = 0;
			$value['update'] = null;
			$search = cloud_get_array($searchArray, $value['username'], 'username');
			if( is_array($search) ) {
				$value['impression_str'] = $search['impression_str'];
				$value['spent_str'] = $search['spent_str'];
				$value['click_str'] = $search['click_str'];
				$value['ctr_str'] = $search['ctr_str'];
				$value['acp_str'] = $search['acp_str'];
				$value['update'] = $search['update'];
			}
		}

		return ['code'=> 0, 'msg'=> '', 'count'=> $total, 'data'=> $items,
			'expand' => Expand::getList($request->sessInfo, 10),
			'bazaar' => Bazaar::getList($request->sessInfo, 1) ];
	}

}
